import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/main/bloc/details_validate_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/person/bloc/my_address_bloc.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/modle/person/ui/add_adress_page.dart';
import 'package:shopping_group/modle/person/ui/my_adress_page.dart';
import 'package:shopping_group/modle/play/ui/fugou_runing_paly_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../play/ui/details_runing_paly_page.dart';

class FuGoodToPalyPage extends StatefulWidget {
  final CommoSpec4AppRecordEntity entity;
  FuGoodToPalyPage({Key key, this.entity}) : super(key: key);

  @override
  _FuGoodToPalyPageState createState() => _FuGoodToPalyPageState();
}

class _FuGoodToPalyPageState extends State<FuGoodToPalyPage> {
  MyAddressBloc _addressBloc;
  List<SouJianRenEntity> _listEntity = [];
  StreamSubscription _selectSubscription;
  StreamSubscription _addSubscription;
  StreamSubscription _validateSubscription;
  StreamSubscription _zfbSubscription;
  DetailsValidateBloc _bloc;
  //DetailsRuningPlayBloc _playBloc;
  // StreamSubscription _zfbStartListSubscription;
  // StreamSubscription _zfbCallblackListSubscription;
  // StreamSubscription _zfbCompleteListSubscription;
  // bool isToZfbPlayView = false;
  String _count = '1';
  @override
  void initState() {
    super.initState();
    _addressBloc = MyAddressBloc();
    _bloc = DetailsValidateBloc();
    _addressBloc.initDate.add(null);
    //_playBloc = DetailsRuningPlayBloc();
    _selectSubscription = eventBus.on<SelectOSouJianRenEvent>().listen((event) {
      List<SouJianRenEntity> temp = [];
      temp.add(event.entity);
      temp.addAll(_listEntity);
      _listEntity = temp;
      _addressBloc.initDate.add(_listEntity);
    });

    _addSubscription = eventBus.on<AddSouJianRenEvent>().listen((event) {
      BaseConstant.adressEntity = event.entity;
      _listEntity.add(event.entity);
      _addressBloc.initDate.add(_listEntity);
    });

    // _zfbCompleteListSubscription =
    //     eventBus.on<ZfbCompeteEvent>().listen((event) {
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   String openType = this.widget.entity.openType;
    //   String orderId = this.widget.entity.orderId;
    //   if (openType == 'order') {
    //     eventBus.fire(RefreshOrderEvent(orderId));
    //     RouteUtil.closeView();
    //   } else if ('fuGood' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
    //   } else if ('fuGoodjuan' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.FUGOU_VIEW_PAGE);
    //   } else if ('dfk' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.DFK_VIEW_PAGE);
    //   } else {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
    //   }
    // });

    // _zfbCallblackListSubscription =
    //     eventBus.on<ZfbCallbackEvent>().listen((event) {
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   Map<String, dynamic> data = {};
    //   data['val'] = event.id;
    //   data['selectId'] = this.widget.entity.selectId;
    //   _playBloc.zfbPlayCompeteDate.add(data);
    // });

    // _zfbStartListSubscription = eventBus.on<ZfbStartEvent>().listen((event) {
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   Map<String, dynamic> data = event.parm.toJson();
    //   data['type'] = BaseConstant.SHOP_TYPE;
    //   _playBloc.zfbPlayDate.add(data);
    // });

    // _zfbSubscription = eventBus.on<ZfbShopEvent>().listen((event) {
    //   Map<String, dynamic> data = {};
    //   data['userId'] = BaseConstant.userId;
    //   data['shopOrderId'] = this.widget.entity.orderId;
    //   data['commoSpecId'] = this.widget.entity.id;
    //   data['shopCt'] = '1';
    //   data['getGoodInfoId'] = BaseConstant.adressEntity.id;
    //   data['payVal'] = this.widget.entity.outPrice;
    //   data['payOption'] = 'PO_ZI_FU_BAO';
    //   data['openType'] = this.widget.entity.openType;
    //   data['orderId'] = this.widget.entity.orderId;
    //   data['custGroupsRelaId'] = this.widget.entity.custGroupsRelaId;
    //   data['selectId'] = '';
    //   isToZfbPlayView = false;
    //   _playBloc.playDate.add(data);
    // });

    _validateSubscription = eventBus.on<ValidateNewShopEvent>().listen((event) {
      //  isToZfbPlayView = true;
      this.widget.entity.count = _count;
      this.widget.entity.valEntity = event.entity;
      if ('Y' == this.widget.entity.isReBuy) {
        RouteUtil.goParameter(FuGouRuningPalyPage(entity: this.widget.entity));
      } else {
        RouteUtil.goParameter(
            DetailsRuningPalyPage(entity: this.widget.entity));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '确认订单'),
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  _showAddressView(),
                  SizedBox(
                    height: 8,
                  ),
                  _shoppingView(),
                  SizedBox(
                    height: 8,
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    decoration: BoxDecoration(
                      color: Colours.title_white,
                    ),
                    child: Row(
                      children: <Widget>[
                        SizedBox(
                          width: 16,
                        ),
                        Expanded(
                          child: WidgetUtils.getTextColorView(
                              '购买数量', Colours.text_2222, Dimens.FONT_SIZE_16),
                        ),
                        GestureDetector(
                          onTap: () {
                            if ('0' == _count) {
                              return;
                            }
                            setState(() {
                              _count = (int.parse(_count) - 1).toString();
                            });
                          },
                          child: Icon(
                            Icons.remove_circle,
                            color: Colours.themeColor,
                            size: 24,
                          ),
                        ),
                        SizedBox(
                          width: 2,
                        ),
                        WidgetUtils.getTextColorView(
                            _count, Colours.text_2222, Dimens.FONT_SIZE_16),
                        SizedBox(
                          width: 2,
                        ),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              _count = (int.parse(_count) + 1).toString();
                            });
                          },
                          child: Icon(
                            Icons.add_circle,
                            color: Colours.themeColor,
                            size: 24,
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                      ],
                    ),
                    // WidgetUtils.itmeStyleView('购买数量', '1',
                    //     contentAlignment: Alignment.centerRight),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    decoration: BoxDecoration(
                      color: Colours.title_white,
                    ),
                    child: WidgetUtils.itmeStyleView('购买数量', '快递',
                        contentAlignment: Alignment.centerRight),
                  ),
                ],
              ),
            ),
            _bottomView(),
          ],
        ),
      ),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                // RouteUtil.closeView();
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    WidgetUtils.getTextColorView(
                        '实付款：', Colors.white, Dimens.FONT_SIZE_16,
                        fontweight: FontWeight.w500),
                    WidgetUtils.getTextColorView(this.widget.entity.outPrice,
                        Colours.themeColor, Dimens.FONT_SIZE_16,
                        fontweight: FontWeight.w500),
                  ],
                ),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.blackground_black_239,
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                if (ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)) {
                  BotToast.showText(text: '请添加收货地址');
                  return;
                }
                Map<String, dynamic> data = {};
                data['userId'] = BaseConstant.userId;
                data['commoSpecId'] = this.widget.entity.id;
                data['realPrice'] = this.widget.entity.outPrice;
                data['shopCt'] = _count;
                _bloc.validateDate.add(data);
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: WidgetUtils.getTextColorView(
                    '去支付', Colors.white, Dimens.FONT_SIZE_16,
                    fontweight: FontWeight.w500),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.text_9C1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _shoppingView() {
    return Container(
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 110.0,
              width: 110.0,
              child: FadeInImage.assetNetwork(
                image: this.widget.entity.imgUrl,
                placeholder: 'images/picture_loading.png' /* 指定gif */,
                fit: BoxFit.contain,
              ),
            ),
            flex: 2,
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  WidgetUtils.getTextColorView(
                    this.widget.entity.name,
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  WidgetUtils.getTextColorView(
                    '生鲜产品不支持拒收，如有破损联系客服秒赔付',
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  WidgetUtils.getTextColorView(
                    '¥ ${this.widget.entity.outPrice}/件',
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }

  Widget _showAddressView() {
    return StreamBuilder(
      stream: _addressBloc.sendinitData,
      initialData: BaseConstant.adressEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }
        int count = _listEntity.length;
        if (count > 0) {
          BaseConstant.adressEntity = _listEntity[0];
        }
        return _addressView();
      },
    );
  }

  Widget _addressView() {
    return GestureDetector(
      onTap: () {
        if (ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)) {
          RouteUtil.goParameter(AddAdressPage(
            action: '新增地址',
          ));
        } else {
          RouteUtil.goParameter(MyAdressPage(
            type: BaseConstant.SELECT_ADRESS,
          ));
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colours.title_white,
        ),
        child: Row(
          children: <Widget>[
            Expanded(
                child: ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)
                    ? Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 16, horizontal: 8),
                        decoration: BoxDecoration(
                          color: Colours.title_white,
                        ),
                        alignment: Alignment.centerLeft,
                        child: WidgetUtils.getTextColorView(
                          '请添加收货地址',
                          Colours.text_2222,
                          Dimens.FONT_SIZE_18,
                        ),
                      )
                    : Container(
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 8, vertical: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                WidgetUtils.getTextColorView(
                                  Utils.reTextNull(
                                      BaseConstant.adressEntity.souJianRenName),
                                  Colours.text_2222,
                                  Dimens.FONT_SIZE_18,
                                ),
                                SizedBox(
                                  width: 32,
                                ),
                                WidgetUtils.getTextColorView(
                                  Utils.reTextNull(BaseConstant
                                      .adressEntity.souJianRenPhone),
                                  Colours.text_2222,
                                  Dimens.FONT_SIZE_18,
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 16,
                            ),
                            WidgetUtils.getTextColorView(
                              Utils.reTextNull(_cityAddrss()),
                              Colours.text_2222,
                              Dimens.FONT_SIZE_16,
                            ),
                          ],
                        ),
                      )),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colours.themeColor,
              size: 32,
            ),
          ],
        ),
      ),
    );
  }

  String _cityAddrss() {
    if (ObjectUtil.isEmptyString(
        BaseConstant.adressEntity.souJianRenProvName)) {
      return '';
    }
    StringBuffer stringBuffer = StringBuffer();
    if (BaseConstant.adressEntity.souJianRenProvName ==
        BaseConstant.adressEntity.souJianRenCityName) {
      stringBuffer
        ..write(BaseConstant.adressEntity.souJianRenCityName)
        ..write(BaseConstant.adressEntity.souJianRenTownName)
        ..write(BaseConstant.adressEntity.souJianRenAddress);
    } else {
      stringBuffer
        ..write(BaseConstant.adressEntity.souJianRenProvName)
        ..write(BaseConstant.adressEntity.souJianRenCityName)
        ..write(BaseConstant.adressEntity.souJianRenTownName)
        ..write(BaseConstant.adressEntity.souJianRenAddress);
    }
    return stringBuffer.toString();
  }

  @override
  void dispose() {
    _selectSubscription?.cancel();
    _validateSubscription?.cancel();
    _addSubscription?.cancel();
    _zfbSubscription?.cancel();
    super.dispose();
  }
}
